package view.common.struts;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.bean.Usuario;

import org.apache.struts.tiles.TilesRequestProcessor;
import view.common.Constants;


public class RequestProcessorPlus extends TilesRequestProcessor {
           
    public RequestProcessorPlus() {
        
    }
    
    @Override
    protected boolean processPreprocess (
        HttpServletRequest request,
        HttpServletResponse response) {
        HttpSession session = request.getSession(false);    
        String path = request.getServletPath();
        
        if (path.equals("/index.jsp")
                || path.equals("/Login.do")) {

            if (session == null || session.getAttribute(Constants.SESSION_USER) == null) {
                if (session.getAttribute("LoginForm") == null) {
                    sessionIsNull(request, response);
                    CustomActionForm frm = new CustomActionForm();
                    frm.setBean(new Usuario());
                    session.setAttribute("LoginForm", frm);
                }
            }
            return super.processPreprocess(request, response);
        }

        if (session != null
                && session.getAttribute(Constants.SESSION_USER) != null) {

            Usuario usuario = (Usuario)session.getAttribute(Constants.SESSION_USER);
            //String accion = path.substring(path.indexOf(request.getContextPath())  + request.getContextPath().length() ) ;
            String accion = path;
            System.out.println("accion:" + accion);

            if(accion!=null && accion.length()>0 && usuario.getFlagAcceso(accion)){
                return super.processPreprocess(request, response);
            }
            
        }

        sessionIsNull(request, response);
        
        return false;
      }
    
      void sessionIsNull(HttpServletRequest request, HttpServletResponse response){
          log.warn("FRAMEWORK - Ended session");
          try{                
            request.getRequestDispatcher("/index.jsp").forward(request,response);
          }catch(Exception ex){
            ex.printStackTrace();
          }      
      }
}
